﻿' Copyright © Microsoft Corporation.  All Rights Reserved.
' This code released under the terms of the 
' Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

Public Class Sheet2

    ''' <summary>
    ''' A string to store the original value in the usernameNamedRange
    ''' control.
    ''' </summary>
    Private userName As String

    ''' <summary>
    ''' Handles the Startup event for the sheet. When the event fires, 
    ''' the value of the usernameNamedRange control will be retrieved
    ''' and saved into userName field.
    ''' </summary>
    ''' <param name="sender">Unused.</param>
    ''' <param name="e">Unused.</param>
    ''' <remarks></remarks>
    Private Sub Sheet2_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
        ' Gets userNameNamedRange initial value
        userName = usernameNamedRange.Value2.ToString()
    End Sub

    Private Sub Sheet2_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown

    End Sub


    ''' <summary>
    ''' A boolean indicating whether the change event has been 
    ''' handled or not.
    ''' control.
    ''' </summary>
    Dim isHandled As Boolean = False

    ''' <summary>
    ''' Handles the NamedRange change event. When this event fires, the 
    ''' original value of the NamedRange control will be restored and a 
    ''' Message Box will be displayed indicating that the user is not 
    ''' authorized to change the value.
    ''' </summary>
    ''' <param name="Target">Unused.</param>
    ''' <remarks></remarks>
    Private Sub usernameNamedRange_Change(ByVal Target As Microsoft.Office.Interop.Excel.Range) Handles usernameNamedRange.Change
        If (isHandled = True) Then
            Return
        End If
        Try
            isHandled = True
            usernameNamedRange.Value2 = userName

            MessageBox.Show("You are not authorized to change this value.", _
              "Document Protection Techniques - Excel", _
              MessageBoxButtons.OK, _
              MessageBoxIcon.Information, _
              MessageBoxDefaultButton.Button1)
        Catch ex As Exception
            MessageBox.Show( _
              ex.Message, _
              "Error handling NamedRange change event.", _
              MessageBoxButtons.OK, _
              MessageBoxIcon.Error, _
              MessageBoxDefaultButton.Button1)
        Finally
            isHandled = False
        End Try

    End Sub
End Class

